package com.atsongyr.springcloud.controller;

import com.atsongyr.springCloud.entity.CommonResult;
import com.atsongyr.springCloud.entity.Payment;
import com.atsongyr.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author songyurui
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 对于注册进行eureka里面的服务，可以通过服务发现来获得该服务的信息
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            return new CommonResult(200, "新增到数据库成功,serverPort: " + serverPort, result);
        } else {
            return new CommonResult(444, "新增失败", null);
        }
    }


    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {

        Payment payment = paymentService.getPaymentById(id);

        if (payment != null) {
            return new CommonResult(200, "查询成功,serverPort: " + serverPort, payment);
        } else {
            return new CommonResult(444, "无对应记录，查询失败，id："+id, null);
        }
    }

    /**
     * 发现问服务各种信息-探寻。
     * 需在启动类增加注解#EnableDisvoverClient
     * @return
     */
    @GetMapping(value = "/payment/discovery")
    public Object discovery() {

        // 获取eureka服务列表信息
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(s -> {
            log.info("*****element:"+s);
        });
        // 查找指定服务名称的服务信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.stream().forEach(serviceInstance ->{
                log.info(serviceInstance.getServiceId()+"\t"+serviceInstance.getHost()+"\t"+serviceInstance.getPort()+"\t"+serviceInstance.getUri());
        });
        return this.discoveryClient;
    }

    /**
     * 手写负载均衡轮询 测试
     * @return
     */
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeOut() {
        try {
            // 测试Feign调用，延时3秒
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }


}
